// 文章分类
const express = require('express');
const router = express.Router()
const { db, genid } = require('../db/DbConnect');

// 获取
router.get('/list', async (req, res) => {
    try {
        let select_category_sql = `
        SELECT * FROM category`
        let _dbres = await db.async.all(select_category_sql, [])
        // delete _dbres
        res.status(200).send({
            code: 200,
            msg: '获取成功',
            _dbres
        })
    } catch (error) {
        res.status(500).send({
            code: 500,
            msg: '获取失败',
            error: error.message
        })
    }
})

// 删除
router.post('/_token/delete', async (req, res) => {
    let { id } = req.body
    try {
        let delete_category_sql = `
        DELETE FROM category WHERE id =?`
        let _dbres = await db.async.run(delete_category_sql, [id])

        res.status(200).send({
            code: 200,
            msg: '删除成功',
        })
    } catch (error) {
        res.status(500).send({
            code: 500,
            msg: '删除失败',
            error: error.message
        })
    }
})

// 修改
router.post('/_token/update', async (req, res) => {
    let { id, name } = req.body
    try {
        let update_category_sql = `
        UPDATE category SET name =? WHERE id =?`
        let _dbres = await db.async.run(update_category_sql, [name, id])

        res.status(200).send({
            code: 200,
            msg: '修改成功',
            name
        })
    } catch (error) {
        res.status(500).send({
            code: 500,
            msg: '修改失败',
            error: error.message
        })
    }
})

// 添加
router.post('/_token/add', async (req, res) => {
    let { name } = req.body
    console.log("name:",name);
    try {
        if(('' + name).trim() === "" || name === undefined || name === null){
            throw new Error('不能为空')
        }
        let insert_category_sql = `
        INSERT INTO category (id, name) VALUES (?, ?)`
        let _dbres = await db.async.run(insert_category_sql, [genid.NextId(), name])

        res.status(200).send({
            code: 200,
            msg: '添加成功',
            name
        })
    } catch (error) {
        res.status(500).send({
            code: 500,
            msg: '添加失败',
            error: error.message
        })
    }
})

module.exports = router
